package panda.li.navigation.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.internal.LinkedTreeMap;
import com.zhy.http.okhttp.OkHttpUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import panda.li.navigation.R;
import panda.li.navigation.adapter.CarsAdapter;
import panda.li.navigation.base.ActivityCollector;
import panda.li.navigation.base.BaseActivity;
import panda.li.navigation.base.MyApplication;
import panda.li.navigation.callback.BaseCallBack;
import panda.li.navigation.constant.Constant;
import panda.li.navigation.entity.CarsInfo;
import panda.li.navigation.utils.Result;
import panda.li.navigation.utils.ToastUtil;

/**
 *
 */
public class CarActivity extends BaseActivity {
    @Bind(R.id.lv_data)
    ListView lv_data;

    @Bind(R.id.btn_car)
    Button btn_car;

    @Bind(R.id.btn_baoyang)
    Button btn_baoyang;

    @Bind(R.id.btn_licheng)
    Button btn_licheng;

    @Bind(R.id.btn_safe)
    Button btn_safe;




    @Bind(R.id.btn_add)
    Button btn_add;
//    @Bind(R.id.tv_title)
//    TextView tv_title;
//    @Bind(R.id.tv_content)
//    TextView tv_content;
//    @Bind(R.id.btn_save)
//    Button btn_save;


    int operateFlag = 0;


    PopupWindow addPpopup;

    PopupWindow detailPopup;



     String tv_title_str;
     String tv_content_str;

    EditText tv_title ;
    EditText tv_content ;


    private CarsAdapter adapter;
    private List<CarsInfo> CarsInfoList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car);
        ButterKnife.bind(this);

        btn_car.setBackgroundColor(Color.GREEN);
        btn_baoyang.setBackgroundColor(Color.GRAY);
        btn_licheng.setBackgroundColor(Color.GRAY);
        btn_safe.setBackgroundColor(Color.GRAY);
        loadData(0);
        operateFlag = 0;
    }


    @OnClick({R.id.btn_car, R.id.btn_baoyang, R.id.btn_licheng, R.id.btn_add, R.id.btn_safe})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_car:// 车辆数据
                btn_car.setBackgroundColor(Color.GREEN);
                btn_baoyang.setBackgroundColor(Color.GRAY);
                btn_licheng.setBackgroundColor(Color.GRAY);
                btn_safe.setBackgroundColor(Color.GRAY);
                loadData(0);
                operateFlag = 0;
                break;
            case R.id.btn_baoyang:// 保养数据
                btn_car.setBackgroundColor(Color.GRAY);
                btn_baoyang.setBackgroundColor(Color.GREEN);
                btn_licheng.setBackgroundColor(Color.GRAY);
                btn_safe.setBackgroundColor(Color.GRAY);
                loadData(1);
                operateFlag = 1;
                break;
            case R.id.btn_licheng:// 里程数据
                btn_car.setBackgroundColor(Color.GRAY);
                btn_baoyang.setBackgroundColor(Color.GRAY);
                btn_licheng.setBackgroundColor(Color.GREEN);
                btn_safe.setBackgroundColor(Color.GRAY);
                loadData(2);
                operateFlag = 2;
                break;
            case R.id.btn_safe:// 保险信息
                btn_car.setBackgroundColor(Color.GRAY);
                btn_baoyang.setBackgroundColor(Color.GRAY);
                btn_licheng.setBackgroundColor(Color.GRAY);
                btn_safe.setBackgroundColor(Color.GREEN);
                loadData(3);
                operateFlag = 3;
                break;

            case R.id.btn_add:
                toAdd();
                break;


        }

    }

    private void loadData(int type) {

        OkHttpUtils.post().url(Constant.LOAD_CARS_LIST)
                .addParams("kind", String.valueOf(type))
                .build()
                .execute(new BaseCallBack<Result>() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.show(MyApplication.getInstance(), e.getMessage());
                    }

                    @Override
                    public void onSuccess(Result response, int ids) {
                        if (response != null) {
                            List<com.google.gson.internal.LinkedTreeMap> datalist = (ArrayList<LinkedTreeMap>) response.getData();
                            try {
                                CarsInfoList = new ArrayList<>();
                                for (com.google.gson.internal.LinkedTreeMap map : datalist) {
                                    Double id = (Double) map.get("id");
                                    Double kind = (Double) map.get("kind");
                                    String title = (String) map.get("title");
                                    String content = (String) map.get("content");
                                    String remark = (String) map.get("remark");
                                    CarsInfo carsinfo = new CarsInfo();
                                    carsinfo.setId(id.intValue());
                                    carsinfo.setKind(kind.intValue());
                                    carsinfo.setTitle(title);
                                    carsinfo.setContent(content);
                                    carsinfo.setRemark(remark);
                                    CarsInfoList.add(carsinfo);
                                }

                                if (CarsInfoList.size() == 0) {
                                    ToastUtil.show(getApplicationContext(), "暂无数据！！！");
                                }

                                adapter = new CarsAdapter(getApplicationContext(), CarsInfoList);
                                lv_data.setAdapter(adapter);
                                lv_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        CarsInfo newsInfo = CarsInfoList.get(i);
                                        detailPopup = new PopupWindow(CarActivity.this);
                                        View popView = LayoutInflater.from(CarActivity.this).inflate(R.layout.item_cars_detail, null);
                                        detailPopup.setContentView(popView);
                                        detailPopup.setFocusable(true);
                                        DisplayMetrics metric = new DisplayMetrics();
                                        getWindowManager().getDefaultDisplay().getMetrics(metric);
                                        int width = metric.widthPixels; // 屏幕宽度（像素）
                                        int height = metric.heightPixels; // 屏幕高度（像素）
                                        detailPopup.setWidth(Integer.parseInt(new DecimalFormat("0").format(width * 1)));
                                        detailPopup.setHeight(Integer.parseInt(new DecimalFormat("0").format(height * 1)));
                                        detailPopup.showAtLocation(CarActivity.this.findViewById(R.id.btn_add), Gravity.CENTER, 0, 0);
                                        popView.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                            }
                                        });

                                        EditText tv_title = (EditText) popView.findViewById(R.id.tv_title);
                                        EditText tv_content = (EditText) popView.findViewById(R.id.tv_content);
                                        tv_title.setText(newsInfo.getTitle());
                                        tv_content.setText(newsInfo.getContent());
                                        Button btn_save = (Button) popView.findViewById(R.id.btn_save);
                                        btn_save.setVisibility(View.GONE);
                                    }
                                });

                                lv_data.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                                    @Override
                                    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        final CarsInfo carsInfo = CarsInfoList.get(i);
                                        detailPopup.dismiss();
                                        new AlertDialog.Builder(CarActivity.this)
                                                .setTitle("信息删除")
                                                .setMessage("是否确认删除")
                                                .setPositiveButton("确认",
                                                        new DialogInterface.OnClickListener() {
                                                            @Override
                                                            public void onClick(DialogInterface dialog, int which) {
                                                                try {
                                                                    OkHttpUtils.post().url(Constant.CARS_DEL)
                                                                            .addParams("id", String.valueOf(carsInfo.getId()))
                                                                            .build()
                                                                            .execute(new BaseCallBack<Result>() {
                                                                                @Override
                                                                                public void onError(Call call, Exception e, int id) {
                                                                                    ToastUtil.show(MyApplication.getInstance(), e.getMessage());
                                                                                }

                                                                                @Override
                                                                                public void onSuccess(Result response, int id) {
                                                                                    if (response != null) {
                                                                                        try {
                                                                                            loadData(operateFlag);
                                                                                        } catch (Exception e) {
                                                                                            e.printStackTrace();
                                                                                        }

                                                                                    }
                                                                                }


                                                                            });
                                                                } catch (Exception e) {
                                                                    ToastUtil.show(MyApplication.getInstance(), "操作失败！");
                                                                }
                                                            }
                                                        })
                                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                    }
                                                })
                                                .show();



                                        return false;
                                    }
                                });

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                });

    }




    public void toAdd() {
        addPpopup = new PopupWindow(CarActivity.this);
        View popView = LayoutInflater.from(CarActivity.this).inflate(R.layout.item_cars_detail, null);
        addPpopup.setContentView(popView);
        addPpopup.setFocusable(true);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        int height = metric.heightPixels; // 屏幕高度（像素）
        addPpopup.setWidth(Integer.parseInt(new DecimalFormat("0").format(width * 1)));
        addPpopup.setHeight(Integer.parseInt(new DecimalFormat("0").format(height * 1)));
        addPpopup.showAtLocation(CarActivity.this.findViewById(R.id.btn_add), Gravity.CENTER, 0, 0);
        popView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        tv_title = (EditText) popView.findViewById(R.id.tv_title);
        tv_content = (EditText) popView.findViewById(R.id.tv_content);



        Button btn_save = (Button) popView.findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    tv_title_str = tv_title.getText().toString().trim();
                    tv_content_str = tv_content.getText().toString().trim();
                    OkHttpUtils.post().url(Constant.CARS_ADD)
                            .addParams("kind", String.valueOf(operateFlag))
                            .addParams("title", tv_title_str)
                            .addParams("content", tv_content_str)
                            .build()
                            .execute(new BaseCallBack<Result>() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    ToastUtil.show(MyApplication.getInstance(), e.getMessage());
                                }

                                @Override
                                public void onSuccess(Result response, int id) {
                                    if (response != null) {
                                        try {
                                            addPpopup.dismiss();
                                            loadData(operateFlag);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }


                            });
                } catch (Exception e) {
                    ToastUtil.show(MyApplication.getInstance(), "操作失败！");
                }
            }
        });


    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
